package com.zl.autocode.common.utils.generator.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

/**
 * 表标题处理
 * @author zhouliang
 *
 */
public class TableTitleUtil {
    private static Pattern TITLE_RULE = Pattern.compile("([ -]){1,}");//标题获取规则
    private static Pattern TITLE_RULE2 = Pattern.compile("(^【.*?】)|(^\\[.*?\\])|(^\\(.*?\\))|(^（.*?）)");//标题获取规则
    private static Pattern TITLE_RULE3 = Pattern.compile("(.*)$|（.*）$");//保留最后的括号说明
    
    /** 按规则解析出标题,也可以自定义传入解析规则*/
    public static String praseTitleByPattern(String str,String code){
        if(StringUtils.isBlank(str)){
            return code;
        }
        //优先顺序
        String title = null;
        str = str.toLowerCase().trim();
        if(str.contains(code)){
            str=str.replace(code, "").trim();
        }
        Matcher titleM = TITLE_RULE2.matcher(str);
        if(titleM.find()){
            title = titleM.group();
            title = title.substring(1, title.length()-1);
        }else{
            String[] titleArr = TITLE_RULE.split(str);
            title = titleArr[0].trim();
            
            if(titleArr.length>1){
                Matcher extraMh = TITLE_RULE3.matcher(str);
                if(extraMh.find()){
                    title = title +extraMh.group();
                }
            }
        }
        if(StringUtils.isNotBlank(title)){
            if(title.length() > 20 && !title.endsWith(")") && !title.endsWith("）")){
                title =  title.substring(0,20).trim();
            }
            title=title.split("(:|：)+",2)[0];
            return title;
        }
        return code;
    }
}
